<template>
  <div class="pagination">
    <!-- 上 -->
    <!-- 当前是第1页就不能点 -->
    <button :disabled="pageNo==1" @click="$emit('listData',pageNo-1)">上一页</button>
    <!-- 当前页>1，此页才需要显示 -->
    <button v-if="startNumAndEndNum.start > 1" @click="$emit('listData',1)" :class="{active:pageNo==1}">1</button>
    <!-- start>2，...才需要显示 -->
    <button v-if="startNumAndEndNum.start > 2">···</button>

    <!-- 中间部分 -->
    <!-- v-for可遍历：数组|数字|字符串|对象 -->
    <!-- 中间连续部分只会显示star-end之间的数字 -->
    <button v-for="(page,index) in startNumAndEndNum.end" :key="index" v-if=" page >= startNumAndEndNum.start" @click="$emit('listData',page)" :class="{active:pageNo==page}">{{page}}</button>

    <!-- 下 -->
    <!-- end<totalPage-1才会显示 -->
    <button v-if="startNumAndEndNum.end < totalPage-1">···</button>
    <!-- end<totalPage才会显示 -->
    <button v-if="startNumAndEndNum.end < totalPage" @click="$emit('listData',totalPage)" :class="{active:pageNo==totalPage}">{{totalPage}}</button>
    <button :disabled="pageNo==totalPage" @click="$emit('listData',pageNo+1)">下一页</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  props: ['pageNo','pageSize','showPageNo','total'],
  //计算属性
  computed:{
    //计算总共页数
    totalPage(){
      return Math.ceil(this.total/this.pageSize);
    },
    //计算连续页码的起始数字和结束数字【重要】
    startNumAndEndNum(){
      //先定义变量存储起始和结束数字
      let start = 0, end = 0;
      //情况1：总页码少于5页，就没有连续页码数
      if(this.showPageNo > this.totalPage){
        start = 1;
        end = this.totalPage;
      }else {
        //情况2：总页数大于5页，连续页码数设置为5
        //注意showPageNo可能取值为5|7
        start = this.pageNo-(this.showPageNo-1)/2;
        end = this.pageNo+(this.showPageNo-1)/2;
        //出现start<1情况，必须纠正
        if(start < 1) {
          start = 1;
          end = this.showPageNo;
        }
        if(end > this.totalPage) {
          //出现end>totalPage情况，必须纠正
          start = this.totalPage-this.showPageNo+1;
          end = this.totalPage;
        }
      }
      return {start,end};
    }
  }
};
</script>

<style scoped>
.pagination {
  position: absolute;
  transform: translate(-50%);
  left: 50%;
  bottom: 4vh;
  text-align: center;
  min-width: 100%;
}

button {
  margin: 0 5px;
  background-color: #f4f4f5;
  color: #606266;
  outline: none;
  border-radius: 2px;
  padding: 0 4px;
  vertical-align: top;
  display: inline-block;
  font-size: 13px;
  min-width: 35.5px;
  height: 28px;
  line-height: 28px;
  cursor: pointer;
  box-sizing: border-box;
  text-align: center;
  border: 0;
  }
  

button[disabled] {
  color: #c0c4cc;
  cursor: not-allowed;
}

button.active {
  cursor: not-allowed;
  background-color: #409eff;
  color: #fff;
}

.active {
  background: skyblue;
}
</style>